const express = require('express');
const axios = require('axios');
const router = express.Router();
const {APPID, APPSECRET} = require('@config/config');
const {generateToken} = require('@utils/jwt');

router.post('/login', async (req, res) => {
  const { code } = req.body
  try {
    const response = await axios.get( `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${APPSECRET}&js_code=${code}&grant_type=authorization_code` )
    const { openid, session_key } = response.data
    if (!openid) { return res.json({ success: false, message: '登录失败' }) };
    const token = generateToken({ openid, session_key });
    res.json({ success: true, token });
  } catch (error) {
    res.json({ success: false, error })
  }
})

module.exports = router
